﻿using Autofac;

namespace RpcCentral.Common
{
    public class IocScope : IDisposable
    {
        private ILifetimeScope _Lifetime;
        private ILifetimeScope _Parent;
        private Action<ILifetimeScope> _DisposableEvent;
        internal IocScope(ILifetimeScope lifetime, Action<ILifetimeScope> disposableEvent)
        {
            _Lifetime = lifetime;
            _DisposableEvent = disposableEvent;
        }
        internal IocScope(ILifetimeScope lifetime, ILifetimeScope parent, Action<ILifetimeScope> disposableEvent)
        {
            _Parent = parent;
            _Lifetime = lifetime;
            _DisposableEvent = disposableEvent;
        }
        public IocScope CreateScore()
        {
            ILifetimeScope lifetime= _Lifetime.BeginLifetimeScope();
            return new IocScope(lifetime, this._Lifetime,new Action<ILifetimeScope>(_rollback));
        }
        private void _rollback(ILifetimeScope scope)
        {
            _Lifetime = scope;
        }

        public T Resolve<T>()
        {
            return _Lifetime.Resolve<T>();
        }
        public T Resolve<T>(string name)
        {
            return _Lifetime.ResolveKeyed<T>(name);
        }
        public void Dispose()
        {
            _Lifetime.Dispose();
            _DisposableEvent(this._Parent);
        }
    }
}
